module.exports = {
  //生成JWT Token
  setJwtToken(data={}){
    const { ctx,app } = this
	  return app.jwt.sign(data,app.config.jwt.secret,app.config.jwt.expiresIn)
	},
  // 解析JWT TOKEN
  getJwtToken(){
    const { ctx,app } = this
    return app.jwt.verify(ctx.request.header.token, app.config.jwt.secret)
  },
  // JWT判断是否过期
  isJwtInvalid(token){
    const { ctx,app } = this
    let user = app.jwt.verify(token, app.config.jwt.secret)
		let nowTime = parseInt(new Date().getTime()/1000)
    let diff = nowTime - (user.iat + app.config.jwt.expiresIn)
    if(diff > 0){
      return true
    }else{
      return false
    }
  },
  // 随机字符串
  randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
      var randomPoz = Math.floor(Math.random() * charSet.length);
      randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
  },
  // 生成TOKEN
  getToken(){
    var guid = '';
    for (var i = 1; i <= 32; i++){
      var n = Math.floor(Math.random()*16.0).toString(16);
      guid +=   n;
      if((i==8)||(i==12)||(i==16)||(i==20))
        guid += '_';
    }
    return guid;
  },
  // redis写入
  redisSet(key,value,seconds=false){
	  let { redis } = this.app
	  value = JSON.stringify(value)
	  if(!seconds){
		  redis.set(key,value)
	  }else{
		  redis.set(key,value,'EX',seconds)
	  }
  },
  // redis读取
  redisGet(key){
	  let { redis } = this.app
	  let result = redis.get(key)
	  return result
  },
  // redis删除
  redisDelete(key){
    let { redis } = this.app
	  let result = redis.del(key)
	  return result
  },
  // 获取登录用户信息
  getUser(){
    return this.redisGet(this.ctx.request.header.token)
  }
}